<template>
  <div class="parent">
    <div class="title">
      告警模板
    </div>
    <el-form ref="ruleFormRef" :rules="rules" :inline="true" :model="formInline" class="demo-form-inline">
      <ElCard class="art-table-card" shadow="never" style="margin-top: 20px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="formInline.name" placeholder="请输入模板名称" clearable />
        </el-form-item>
        <el-form-item label="模板编号" prop="modelNo">
          <el-input v-model="formInline.modelNo" placeholder="输入模板编号" clearable />
        </el-form-item>
        <el-form-item label="通知类型" prop="notifyType">
          <el-select @change="notifyTypeChange" v-model="formInline.notifyType" placeholder="请选择通知类型" clearable>
            <el-option label="阿里云短信" value="1" :disabled="true" />
            <el-option label="邮箱" value="2" />
            <el-option label="钉钉" value="3" :disabled="true" />
            <el-option label="公众号" value="4" :disabled="true" />
            <el-option label="http" value="5" :disabled="true" />
          </el-select>
        </el-form-item>
        <el-form-item label="监控模型" prop="monitorModelId">
          <el-select @change="monitorModelChange" v-model="formInline.monitorModelId" placeholder="请选择监控模型" clearable>
            <el-option :label="value.name" :value="value.id" v-for="value in monitorModels" />
          </el-select>
        </el-form-item>
      </ElCard>

      <ElCard class="art-table-card" shadow="never" style="margin-top: 20px">
        <el-button link type="primary" style="float: right;" @click.stop="addR()">新增规则</el-button>
        <div @click="">
          <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="date" label="测点名称" width="180">
              <template #default="{ row, $index }">
                <el-select v-if="editingIndex === $index" v-model="row.attKey" placeholder="请选择测点名称" clearable
                  @click.stop style="width: 100%;">
                  <el-option :label="value.attName" :value="value.attKey" v-for="value in monitorModelAtts" />
                </el-select>
                <el-select :disabled="true" v-else v-model="row.attKey" placeholder="请选择测点名称" clearable @click.stop
                  style="width: 100%;">
                  <el-option :label="value.attName" :value="value.attKey" v-for="value in monitorModelAtts" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="date" label="告警等级" width="180">
              <template #default="{ row, $index }">
                <!-- 1 紧急 2 告警 3 预警 -->
                <el-select v-if="editingIndex === $index" v-model="row.grade" placeholder="请选择数据类型" clearable
                  @click.stop style="width: 100%;">
                  <el-option label="紧急" value="1" />
                  <el-option label="告警" value="2" />
                  <el-option label="预警" value="3" />
                </el-select>
                <el-select :disabled="true" v-else v-model="row.grade" placeholder="请选择数据类型" clearable @click.stop
                  style="width: 100%;">
                  <el-option label="紧急" value="1" />
                  <el-option label="告警" value="2" />
                  <el-option label="预警" value="3" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="测点key数据类型" width="180">
              <template #default="{ row, $index }">
                <el-select v-if="editingIndex === $index" v-model="row.attKeyType" placeholder="请选择数据类型" clearable
                  @click.stop style="width: 100%;">
                  <el-option label="数值" value="1" />
                  <el-option label="日期yyyy-MM-dd" value="2" />
                  <el-option label="日期yyyy-MM-dd HH:mm:ss" value="3" />
                </el-select>
                <el-select :disabled="true" v-else v-model="row.attKeyType" placeholder="请选择数据类型" clearable @click.stop
                  style="width: 100%;">
                  <el-option label="数值" value="1" />
                  <el-option label="日期yyyy-MM-dd" value="2" />
                  <el-option label="日期yyyy-MM-dd HH:mm:ss" value="3" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="比较符">
              <template #default="{ row, $index }">
                <!-- '1 > ,2>=,3=,4<,5<=', -->
                <el-select v-if="editingIndex === $index" v-model="row.conditionTag" placeholder="请选择比较符" @click.stop
                  clearable style="width: 100%;">
                  <el-option label=">" value="1" />
                  <el-option label=">=" value="2" />
                  <el-option label="=" value="3" />
                  <el-option label="<" value="4" />
                  <el-option label="<=" value="5" />
                </el-select>
                <el-select :disabled="true" v-else v-model="row.conditionTag" placeholder="请选择比较符" @click.stop clearable
                  style="width: 100%;">
                  <el-option label=">" value="1" />
                  <el-option label=">=" value="2" />
                  <el-option label="=" value="3" />
                  <el-option label="<" value="4" />
                  <el-option label="<=" value="5" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="告警阈值">
              <template #default="{ row, $index }">
                <el-input v-if="editingIndex === $index" v-model="row.dataValue" @click.stop />
                <span v-else>{{ row.dataValue }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="静默时间（分钟）">
              <template #default="{ row, $index }">
                <el-input v-if="editingIndex === $index" v-model="row.silenceTime" @click.stop />
                <span v-else>{{ row.silenceTime }}</span>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" min-width="120">
              <template #default="{ row, $index }">
                <el-button link type="primary" size="small" @click.stop="handleDelete($index)">
                  删除
                </el-button>
                <el-button v-if="editingIndex === $index" link type="primary" size="small" @click.stop="handleSave">
                  保存
                </el-button>
                <el-button v-else link type="primary" size="small" @click.stop="handleEdit($index)">
                  编辑
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </ElCard>
      <ElCard class="art-table-card" shadow="never" style="" v-if="formInline.notifyType == '2'">
        <div>
          <!-- 输入框列表 -->
          <div v-for="(item, index) in formInline.notifyData" :key="index" class="input-item">
            <el-input v-model="formInline.notifyData[index]" placeholder="请输入邮箱" clearable />
            <el-button type="danger" :icon="Delete" v-if="formInline.notifyData.length > 1"
              @click="removeItem(index)" />
          </div>
          <!-- 添加按钮 -->
          <el-button type="primary" @click="addItem" class="add-btn">
            添加邮箱
          </el-button>
        </div>
      </ElCard>
      <ElCard class="art-table-card" shadow="never" style="">
        <el-button type="primary" @click="onSubmit(ruleFormRef)" style="float: right;">保存</el-button>
      </ElCard>
    </el-form>


  </div>
</template>

<script setup lang="ts">
import { ref,onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { reactive } from 'vue'
import { BmslzService } from '@/api/bmslzApi'
import { ElMessage } from 'element-plus'

import {
  Delete
} from '@element-plus/icons-vue'
const router = useRouter();
const route = useRoute();
const modelId = route.query.id as string;
const tableData = ref([
  {
    id: '',
    attKey: '',
    attKeyType: '',
    conditionTag: '',
    dataValue: '',
    silenceTime: '',
    grade: ''//1 紧急 2 告警 3 预警
  }
]);
const monitorModels = ref<any[]>([]) // 监控模型数组
const monitorModelAtts = ref<any[]>([]) // 监控模型att数组

const editingIndex = ref(-1);
const originalData = ref({});

const ruleFormRef = ref<FormInstance>()
interface RuleForm {
  name: string
  monitorModelId: string
  modelNo: string,
  notifyType: string
}
const rules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: '模板名称不能为空', trigger: 'blur' },
    { min: 1, max: 50, message: '模板名称要在50个字符内', trigger: 'blur' }
  ],
  monitorModelId: [
    { required: true, message: '监控模型编号不能为空', trigger: 'blur' }
  ],
  modelNo: [
    { required: true, message: '模板编号不允许为空', trigger: 'blur' },
    { min: 1, max: 50, message: '模板编号要在50个字符内', trigger: 'blur' }
  ],
  notifyType: [
    { required: true, message: '通知类型不能为空', trigger: 'blur' }
  ],
})

onMounted(async () => {
  //如果传入id说明是修改 否则就是新增
  const modelId = route.query.id as string;
  //清空数据
  formInline.name = ''
  formInline.monitorModelId = ''
  formInline.modelNo = ''
  formInline.notifyType = ''
  formInline.notifyData = []
  tableData.value = [];
  await queryMonitorModels()

  if (!modelId) {
    return;
  }
  await queryById();

});
// 查询模板详情
const queryById = async () => {
  try {
    //查询模板详情
    const data = await BmslzService.alarmModelQueryById({
      id: modelId
    })
    if (!data) {
      ElMessage.error('不存在');
      router.go(-1); // -1 表示返回上一页
    }

    //表单基础数据回显
    formInline.name = data.name;
    formInline.monitorModelId = data.monitorModelId
    formInline.modelNo = data.modelNo
    formInline.notifyType = data.notifyType
    formInline.notifyData = JSON.parse(data.notifyData)
    const parsedData: any[] = data.rules
    //att数据回显
    tableData.value = parsedData ? parsedData : []

    const foundItem = monitorModels.value.find(item => item.id === formInline.monitorModelId);
    monitorModelAtts.value = JSON.parse(foundItem.att)
  } catch (err) {

  } finally {
  }
};

// 查询可选监控模型
const queryMonitorModels = async () => {
  try {
    //查询模板详情
    const data = await BmslzService.monitorModelList({
      pageNo: 1,
      pageSize: 9999,
      name: ''
    })
    monitorModels.value = data.records;
  } catch (err) {

  } finally {
  }
};

// 删除行
const handleDelete = (index: any) => {
  tableData.value.splice(index, 1);
};

// 新增行
const addR = () => {
  tableData.value.push({
    id: '',
    attKey: '',
    attKeyType: '',
    conditionTag: '',
    dataValue: '',
    silenceTime: '',
    grade: ''//1 紧急 2 告警 3 预警
  })
};
const monitorModelChange = (value: any) => {
  tableData.value = [];
  const foundItem = monitorModels.value.find(item => item.id === value);
  monitorModelAtts.value = JSON.parse(foundItem.att)
}
const notifyTypeChange = (value: any) => {
  formInline.notifyData = [];
}

// 编辑行
const handleEdit = (index: any) => {
  // 保存原始数据以便取消编辑
  originalData.value = { ...tableData.value[index] };
  editingIndex.value = index;
};

// 保存编辑
const handleSave = () => {
  editingIndex.value = -1;
  originalData.value = {};
};

// 点击行外保存
const handleClickOutside = () => {
  if (editingIndex.value !== -1) {
    handleSave();
  }
};

// 如果需要取消编辑功能，可以添加：
// const handleCancel = () => {
//   if (editingIndex.value !== -1) {
//     tableData.value[editingIndex.value] = { ...originalData.value };
//     editingIndex.value = -1;
//   }
// };

const formInline = reactive({
  name: '',
  modelNo: '',
  notifyType: '',
  monitorModelId: '',
  notifyData: ['']
})

// 添加输入项
const addItem = () => {
  formInline.notifyData.push('');
};

// 移除输入项
const removeItem = (index: any) => {
  formInline.notifyData.splice(index, 1);
};

const onSubmit = async (formEl: FormInstance | undefined) => {
  let returnT = ref<boolean>(false);
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (!valid) {
      ElMessage.error('数据填写不完整');
      returnT.value = true
    }
  })
  console.log(tableData)
  for (const item of tableData.value) {
    if (!item.attKey || !item.attKeyType || !item.conditionTag
      || !item.dataValue || !item.silenceTime || !item.grade) {
      ElMessage.error('测点数据填写不完整');
      returnT.value = true;
      break; // ✅ 直接退出循环
    }
  }
  if (returnT.value) {
    return;
  }
  console.log('submit!')
  if (!modelId) {
    //新增模板
    const data = await BmslzService.alarmModelAdd({
      modelNo: formInline.modelNo,
      monitorModelId: formInline.monitorModelId,
      name: formInline.name,
      notifyType: formInline.notifyType,
      notifyData: formInline.notifyData.length > 0 ? JSON.stringify(formInline.notifyData) : '',
      rules: tableData.value
    })
  } else {
    //修改模板
    const { name } = await BmslzService.alarmModelEdit({
      id: modelId,
      modelNo: formInline.modelNo,
      monitorModelId: formInline.monitorModelId,
      name: formInline.name,
      notifyType: formInline.notifyType,
      notifyData: JSON.stringify(formInline.notifyData),
      rules: tableData.value
    })
  }
  ElMessage.success('操作成功！');
  router.go(-1); // -1 表示返回上一页
}

</script>

<style lang="scss" scoped>
.el-input {
  width: 100%;
}

.parent {
  padding: 0 0 0 20px;

  .title {
    color: #101010;
    font-size: 20px;
    font-weight: bold;
  }
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}


.input-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.input-item .el-input {
  flex: 1;
  margin-right: 10px;
}

.add-btn {
  margin-top: 10px;
}
</style>
